#include "settingsdialog.h"
#include "ui_settingsdialog.h"
#include <QProcess>
#include <QDebug>
#include <qfile.h>

SettingsDialog::SettingsDialog(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::SettingsDialog)
{
    ui->setupUi(this);
    // 初始化 lineEdit
    ui->lineEdit->setText(QString::number(Widget::temperatureThreshold));
    updateLineEditState(false);



    //亮度调节
    ui->slider_light->setRange(0, 7); // 设置滑动条的范围为0至7
    ui->slider_light->setSingleStep(1); // 设置滑动条步长为1

    QFile file("/sys/devices/platform/backlight/backlight/backlight/max_brightness");
    int value = 0;
    // 打开文件进行读取
    if (file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
       // 使用 QTextStream 读取文件内容
       QTextStream in(&file);
       QString line = in.readLine();

       // 将读取的值转换为整数
       bool ok;
       value = line.toInt(&ok);
    }
    ui->slider_light->setValue(value);
    ui->label_light->setText(QString::number(value));

    // 连接滑动条的valueChanged()信号到槽函数。 修改屏幕亮度
    connect(ui->slider_light, &QSlider::valueChanged, [&]() {
       // 获取整数值
       int intValue = ui->slider_light->value();
       ui->label_light->setText(QString::number(intValue));

       // 构造要执行的命令
       QString command = "echo " + QString::number(intValue) +
                         " > /sys/class/backlight/backlight/brightness";
       qDebug() << "command is :" << command;


       // 执行命令
       QProcess process;
       process.start("/bin/sh", QStringList() << "-c" << command);
       if (!process.waitForFinished()) {
          qDebug() << "Failed to execute command:" << process.errorString();
          return;
       }
    });




}

SettingsDialog::~SettingsDialog()
{
    delete ui;
}

void SettingsDialog::updateLineEditState(bool editable)
{
    ui->lineEdit->setEnabled(editable);
    if (!editable) {
        ui->lineEdit->setText(QString::number(Widget::temperatureThreshold));
    }
}

void SettingsDialog::on_pBtn_back_clicked()
{
    this->hide();
    emit backToMainPage();
}

void SettingsDialog::on_pushButton_clicked()
{
    // 解锁 lineEdit
    updateLineEditState(true);
}

void SettingsDialog::on_pushButton_2_clicked()
{
    // 获取 lineEdit 中的值
    bool ok;
    double value = ui->lineEdit->text().toDouble(&ok);

    if (ok && value >= 1 && value <= 100) {
        // 如果输入合法，保存值到 Widget::temperatureThreshold
        Widget::temperatureThreshold = value;
        // 锁定 lineEdit
        updateLineEditState(false);
    } else {
        // 如果输入不合法，弹出警告框
        QMessageBox::warning(this, tr("警告"), tr("请输入合法信息"));
        // 锁定 lineEdit 并恢复原值
        updateLineEditState(false);
    }
}
